import { ref, onMounted, onBeforeUnmount, onUnmounted } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
import { useIntervalFn } from '@vueuse/shared'

export function useWindowScroll () {
  const y = ref(0)
  const x = ref(0)

  const onScroll = () => {
    // console.og(document.documentElement.scrollTop)
    // console.log(window.pageYoffset)
    y.value = document.documentElement.scrollTop
    x.value = document.documentElement.scrollLeft
  }

  onMounted(() => {
    window.addEventListener('scroll', onScroll)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('scroll', onScroll)
  })

  return {
    y,
    x
  }
}

/**
 * 用于懒加载数据
 * @param {*} apiFn 懒加载数据的接口
 * @returns target: 需要绑定的DOM对象  result: 结果数据
 */
export const useLazyData = (apiFn) => {
  // 需要
  // 1. 被观察的对象
  // 2. 不同的API函数
  const target = ref(null)
  const result = ref([])
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }], observerElement) => {
      if (isIntersecting) {
        stop()
        // 调用API获取数据
        apiFn().then(data => {
          result.value = data.result
        })
      }
    },
    {
      threshold: 0
    }
  )
  // 返回--->数据（dom,后台数据）
  return { target, result }
}

/**
 * 倒计时逻辑
 * @param {*} count
 * @returns
 */
export const useCountDown = () => {
  const time = ref(0)
  const { pause, resume } = useIntervalFn(() => {
    time.value--
    if (time.value === 0) {
      pause()
    }
  },
  1000,
  {
    immediate: false
  }
  )
  onUnmounted(() => {
    pause()
  })
  const start = () => {
    time.value = 60
    resume()
  }
  return {
    time,
    start
  }
}
